package com.example.myapplication01.jetpack.lifecycle;

import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.Chronometer;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

public class MyChronometer extends Chronometer implements LifecycleEventObserver {

    private long elapsedTime;

    public MyChronometer(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    public void onStateChanged(@NonNull LifecycleOwner lifecycleOwner, @NonNull Lifecycle.Event event) {
        if (event.equals(Lifecycle.Event.ON_PAUSE)) {
            elapsedTime = SystemClock.elapsedRealtime() - getBase();
            stop();
        } else if (event.equals(Lifecycle.Event.ON_RESUME)){
            setBase(SystemClock.elapsedRealtime() - elapsedTime);
            start();
        }
    }
}
